/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Session;
import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.controller.WorkoutMailJob;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Exercise;
import edu.cmu.fithub.db.bean.Schedule;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.db.bean.Workout;

public class AddWorkoutAction extends Action {

	public AddWorkoutAction() {
	}

	public String getName() {
		return "addWorkout.do";
	}

	public String perform(HttpServletRequest request) {

		try {
			List<String> errors = new ArrayList<String>();
			request.setAttribute("errors", errors);
			int i;
			String workoutMessage = "";
			Workout[] workout;
			workout = new Workout[10];
			Session dbSession = DBHelper.getSessionFactory().openSession();
			User user = (User) request.getSession().getAttribute("user");

			int uid = user.getUserId();
			String day = request.getParameter("day").substring(0, 3);
			int hour = Integer.parseInt(request.getParameter("hour"));
			int minute = Integer.parseInt(request.getParameter("minutes"));

			dbSession.beginTransaction();

			String query = "select max(workoutId) from Workout where userId='"
					+ user.getUserId() + "'";
			List list = dbSession.createQuery(query).list();

			Integer workoutId = 0;
			if (list.get(0) != null) {
				workoutId = (Integer) list.get(0) + 1;
			}
			
			for (i = 0; i < 10; i++) {
				String ex_str = request.getParameter("exercise" + (i+1));
				String[] split_ex_str = ex_str.split(";");
				String reps_str = request.getParameter("reps" + (i+1));
				if (ex_str != "" && reps_str != "") {
					if(ex_str.matches(".*[<>].*")) {
						errors.add("Bad workout choice");
					}
					if(!reps_str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
						errors.add("Workout reps should be a valid number");
					}
					if (errors.size() !=0 ) {
						return  "displayAddWorkout.do";
					}
					Exercise ex = new Exercise();
					int exId = Integer.parseInt(split_ex_str[0]);
					String exName = split_ex_str[1];
					ex.setId(exId);
					ex.setName(exName);
					int reps = Integer.parseInt(reps_str);
					workout[i] = new Workout();
					workout[i].setExercise(ex);
					workout[i].setReps(reps);
					workout[i].setUserId(uid);
					workout[i].setWorkoutId(workoutId);
					workoutMessage += "<li> " +  ex.getName() + "  (" + reps +") reps </li>";
					dbSession.save(workout[i]);
				} else {
					break;
				}
			}
			if (i!=0) {
				workoutMessage = "Hi " + user.getFirstName()+ ", You have a workout scheduled now. The following"
				+ " are the exercises scheduled: <ol>" + workoutMessage + "</ol> <br /> Stay healthy, <br /> Zeke Man";
			} else {
				errors.add("No exercise added");
				return "displayAddWorkout.do";
			}
			int schedId = WorkoutMailJob
					.addWorkoutSchedule(
							user.getEmail(),
							workoutMessage,
							WorkoutMailJob.getSchedString(day, hour, minute));

			Schedule sched = new Schedule();
			sched.setDay_of_week(Integer.parseInt(request.getParameter("day")
					.substring(3)));
			sched.setDay(day);
			sched.setHour(hour);
			sched.setId(schedId);
			sched.setMinute(minute);
			sched.setUserId(user.getUserId());
			sched.setWorkoutId(workoutId);

			dbSession.save(sched);
			dbSession.getTransaction().commit();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			System.out.println("NullPointerException");
			e.printStackTrace();
		}

		return "workoutsuccess.jsp";
	}
}
